#!/usr/bin/ruby

APP_NAME = "ical2csv.rb"
APP_VERSION = "0.2"

require 'optparse'
require 'csv'
require 'rubygems'
require 'osx/cocoa'

include OSX

NSBundle.bundleWithPath("/System/Library/Frameworks/CalendarStore.framework").load
ns_import :CalendarStore


class Numeric
	
	def to_s_as_time
		 NSDate.dateWithTimeIntervalSince1970(self).description
	end
	
end

DEFAULT_CALENDAR = "Call Log"
START_DATE = NSDate.dateWithNaturalLanguageString("January 1, 2008 12:00 AM")
END_DATE = NSDate.dateWithNaturalLanguageString("July 1, 2008 12:00AM")

outPipe = $stdout
calendarName = DEFAULT_CALENDAR
startDate = START_DATE
endDate = END_DATE
deleteExportedEvent = false

$verboseMessages = true
oparse = OptionParser.new {|op|
	op.banner = "Usage : #{APP_NAME} [options] [CALENDARNAME]"
	op.on("-v","--verbose","Run verbosely") {
		$verboseMessages = true
	}
	op.on("-c CALENDAR", "Name of calendar to export "+
	                      "(default is 'Call Log')") {|val|
	  calendarName = val
	}
	op.on("-0","Don't copy events with zero duration.",
	"(Incomplete/Unanswered calls)") {
		excludeIncompleteCalls = true
	}
	op.on("-d","Delete event after exporting") {
	  deleteExportedEvent = true
	}
	op.on_tail("-h","-?","Show this message.") {
		puts op
		exit(0)
	}
}

args = oparse.parse!(ARGV)

cs = CalCalendarStore.defaultCalendarStore

calendar = cs.calendars.detect { |cal| cal.title == calendarName }

pred = CalCalendarStore.eventPredicateWithStartDate_endDate_calendars(
          startDate,endDate,[calendar])

events = cs.eventsWithPredicate(pred)

csv = CSV::Writer.generate(outPipe,',')

csv << ['start date','end date','title','notes','location']
events.to_ary.each do |event|
  csv << [event.startDate, event.endDate,event.title,event.notes,event.location]
  if (deleteExportedEvent)
    cs.removeEvent_span_error(event, 0 ,nil)
  end
end

outPipe.close
exit(0)